package org.example.supplychain.controller;

import jakarta.servlet.http.HttpSession;
import org.example.supplychain.domain.User;
import org.example.supplychain.service.InventoryService;
import org.example.supplychain.service.SupplierService;
import org.example.supplychain.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class LoginController {

    @Autowired
    private UserService userService;
	@Autowired
	private SupplierService supplierService;
	@Autowired
	private InventoryService inventoryService;

    @GetMapping("/login")
    public String login() {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam(value = "username") String username, @RequestParam(value = "password") String passwd,
    HttpSession session, Model model) {
        User existingUser = userService.getUserByUserName(username);
        if (existingUser != null && existingUser.getPassword().equals(passwd)) {
            session.setAttribute("name", username);
            //switch ()  //根据用户等级跳转页面
            //第一次迭代只展示仓库管理员页
            //因此用任意存在的账户直接跳转仓库管理员界面
            //未做账户安全控制，也可以直接访问，仅作展示
	        return switch (existingUser.getRole()) {
		        case "系统管理员" -> {
					session.setAttribute("isTotalAdmin", true);
					yield 	"sysAdmin";
		        }
		        case "采购员" -> "order";
		        case "仓库管理员" -> "inventoryKeeper";
		        default -> "login";
	        };
        } else {
            model.addAttribute("error", "Invalid username or password");
            return "login";
        }
    }
	@GetMapping("/logout")
	public String logout(HttpSession session){
		session.invalidate();
		return "login";
	}

//    @GetMapping("/register")
//    public String register(){
//        return "register";
//    }
//
//    @PostMapping("/register")
//    public String register(@RequestParam(value = "username") String username, @RequestParam(value = "password") String passwd,
//                           @RequestParam(value = "email") String email, Model model){
//        if(userService.getUserByUserName(username)!=null){
//            model.addAttribute("registerError", "该用户已注册");
//            return "register";
//        }else {
//            User user = new User();
//            user.setUser_name(username);
//            user.setPassword(passwd);
//            user.setEmail(email);
//            user.setRole("user");
//            user.setCreateDate(new java.util.Date());
//            userService.addUser(user);
//            return "login";
//        }
//    }
}